import type { ProColumns } from '@ant-design/pro-components';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { arrayMoveImmutable, useRefFunction } from '@ant-design/pro-components';
import type { BadgeProps } from 'antd';
import { Badge, Button } from 'antd';
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
// @ts-ignore
import styles from './split.less';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';
import { MenuOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProFormUploadButton,
} from '@ant-design/pro-components';

import './split.less';

const DragHandle = SortableHandle(() => (
  <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
));

const DetailList = (props: any) => {
  const { ip } = props;
  const [tableListDataSource, setTableListDataSource] = useState([
    {
      步骤名称: '文献阅读',
      是否共享材料: '是',
      阶段结束文件: '文献综述',
      key: 0,
      index: 0,
    },
    {
      步骤名称: '开题阶段',
      是否共享材料: '是',
      阶段结束文件: '开题报告',
      key: 1,
      index: 1,
    },
    {
      步骤名称: '中期阶段',
      是否共享材料: '是',
      阶段结束文件: '中期报告',
      key: 2,
      index: 2,
    },
    {
      步骤名称: '预答辩阶段',
      是否共享材料: '是',
      阶段结束文件: '预答辩报告',
      key: 3,
      index: 3,
    },
    {
      步骤名称: '毕业答辩阶段',
      是否共享材料: '是',
      阶段结束文件: '毕业论文',
      key: 4,
      index: 4,
    },
  ]);

  const SortableItem = SortableElement((props: any) => <tr {...props} />);
  const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

  const onSortEnd = useRefFunction(
    ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
      if (oldIndex !== newIndex) {
        const newData = arrayMoveImmutable(
          [...tableListDataSource],
          oldIndex,
          newIndex,
        ).filter((el) => !!el);
        setTableListDataSource([...newData]);
      }
    },
  );

  const DraggableContainer = (props: any) => (
    <SortContainer
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow = (props: any) => {
    const { className, style, ...restProps } = props;
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = tableListDataSource.findIndex(
      (x) => x.index === restProps['data-row-key'],
    );
    return <SortableItem index={index} {...restProps} />;
  };

  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      render: () => <DragHandle />,
    },
    {
      title: '步骤名称',
      key: '步骤名称',
      dataIndex: '步骤名称',
    },
    {
      title: '是否共享材料',
      key: '是否共享材料',
      dataIndex: '是否共享材料',
    },
    {
      title: '阶段结束文件',
      key: '阶段结束文件',
      dataIndex: '阶段结束文件',
    },
    {
      title: '操作',
      key: 'option',
      // width: 80,
      valueType: 'option',
      render: () => [<a key="a">模板下载</a>, <a key="b">删除</a>],
    },
  ];

  useEffect(() => {
    if (ip !== '研究生培养流程') {
      setTableListDataSource([
        {
          步骤名称: '步骤一',
          是否共享材料: '是',
          阶段结束文件: '步骤一文件',
          key: 0,
          index: 0,
        },
        {
          步骤名称: '步骤二',
          是否共享材料: '是',
          阶段结束文件: '步骤二文件',
          key: 1,
          index: 1,
        },
        {
          步骤名称: '步骤三',
          是否共享材料: '是',
          阶段结束文件: '步骤三文件',
          key: 2,
          index: 3,
        },
      ]);
    } else {
      setTableListDataSource([
        {
          步骤名称: '文献阅读',
          是否共享材料: '是',
          阶段结束文件: '文献综述',
          key: 0,
          index: 0,
        },
        {
          步骤名称: '开题阶段',
          是否共享材料: '是',
          阶段结束文件: '开题报告',
          key: 1,
          index: 1,
        },
        {
          步骤名称: '中期阶段',
          是否共享材料: '是',
          阶段结束文件: '中期报告',
          key: 2,
          index: 2,
        },
        {
          步骤名称: '预答辩阶段',
          是否共享材料: '是',
          阶段结束文件: '预答辩报告',
          key: 3,
          index: 3,
        },
        {
          步骤名称: '毕业答辩阶段',
          是否共享材料: '是',
          阶段结束文件: '毕业论文',
          key: 4,
          index: 4,
        },
      ]);
    }
  }, [ip]);

  return (
    <ProTable
      columns={columns}
      dataSource={tableListDataSource}
      pagination={{
        pageSize: 6,
        showSizeChanger: false,
      }}
      rowKey="key"
      toolBarRender={false}
      search={false}
      components={{
        body: {
          wrapper: DraggableContainer,
          row: DraggableBodyRow,
        },
      }}
      // extra={}
    />
  );
};

const IPList = (props: any) => {
  const { onChange, ip } = props;

  const columns = [
    {
      title: '流程名称',
      key: 'flowName',
      dataIndex: 'flowName',
      // render: (_, item) => {
      //     return <Badge status={item.status} text={item.ip} />;
      // },
    },
    {
      title: '创建时间',
      key: '创建时间',
      dataIndex: '创建时间',
      // render: () => {
      //     return
      // }
    },
    {
      title: '创建者',
      key: '创建者',
      dataIndex: '创建者',
    },
  ];

  return (
    <ProTable
      columns={columns}
      rowKey="id"
      dataSource={[
        {
          id: '1001',
          flowName: '研究生培养流程',
          创建时间: '2022-04-04',
          创建者: '李老师',
        },
        {
          id: '1002',
          flowName: '其他流程1',
          创建时间: '2022-05-04',
          创建者: '王老师',
        },
        {
          id: '1003',
          flowName: '其他流程2',
          创建时间: '2022-06-04',
          创建者: '刘老师',
        },
      ]}
      // rowClassName={(record) => {
      //     return record.ip === ip ? styles['split-row-select-active'] : '';
      // }}
      toolbar={{
        search: {
          onSearch: (value) => {
            alert(value);
          },
        },
        actions: [
          <ModalForm
            title="新建流程"
            trigger={
              <Button type="primary">
                {/* <PlusOutlined /> */}
                新建流程
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              // await waitTime(2000);
              console.log(values.name);
              // message.success('提交成功');
              return true;
            }}
          >
            <ProForm.Group>
              <ProFormText width="md" name="name" label="流程名称" />
              <ProFormText
                width="md"
                name="创建者"
                label="创建者"
                initialValue={'刘老师'}
                disabled
              />
              {/* <ProFormDateRangePicker width="md" name="计划起止时间" label="计划起止时间" /> */}
            </ProForm.Group>

            <ProFormList
              name="步骤信息"
              label="步骤信息"
              rules={[
                {
                  validator: async (_, value) => {
                    console.log(value);
                    if (value && value.length > 0) {
                      return;
                    }
                    throw new Error('至少要有一项！');
                  },
                },
              ]}
              creatorButtonProps={{
                creatorButtonText: '添加步骤',
              }}
            >
              <ProFormGroup key="group">
                <ProFormText
                  width="sm"
                  rules={[
                    {
                      required: true,
                    },
                  ]}
                  name="步骤名称"
                  label="步骤名称"
                />
                <ProFormSelect
                  label="是否共享"
                  name="type"
                  width="xs"
                  valueEnum={{
                    是: '是',
                    否: '否',
                  }}
                />
                <ProFormUploadButton
                  width="sm"
                  name="上传文档模板"
                  label="上传文档模板"
                  max={1}
                  fieldProps={{
                    name: 'file',
                  }}
                  action="/upload.do"
                />
              </ProFormGroup>
            </ProFormList>
          </ModalForm>,
        ],
      }}
      options={false}
      pagination={false}
      search={false}
      onRow={(record) => {
        return {
          onClick: () => {
            if (record.flowName) {
              onChange(record.flowName);
            }
          },
        };
      }}
    />
  );
};

export default () => {
  const [ip, setIp] = useState('研究生培养流程');

  return (
    <PageContainer
      extra={[
        <Button key="3">操作</Button>,
        <Button key="2">操作</Button>,
        <Button
          key="1"
          type="primary"
          onClick={() => {
            // console.log(ipListDataSource);
          }}
        >
          主操作
        </Button>,
      ]}
    >
      <ProCard split="vertical">
        <ProCard colSpan="35%" ghost>
          <IPList onChange={(flowName: any) => setIp(flowName)} ip={ip} />
        </ProCard>
        <ProCard
          title={ip}
          extra={
            <ModalForm
              title="添加步骤"
              trigger={
                <Button type="primary">
                  {/* <PlusOutlined /> */}
                  添加步骤
                </Button>
              }
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                // await waitTime(2000);
                console.log(values.name);
                // message.success('提交成功');
                return true;
              }}
            >
              <ProForm.Group>
                <ProFormText width="md" name="步骤名称" label="步骤名称" />
                <ProFormText
                  width="sm"
                  name="创建者"
                  label="创建者"
                  initialValue={'刘老师'}
                  disabled
                />
              </ProForm.Group>
            </ModalForm>
          }
        >
          <DetailList ip={ip} />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};
